package 剑指offer;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;

/**
 * @description:
 * @author: ywk
 * @date: 2020-11-01
 */
public class 字符串的排列 {
    static ArrayList<String> list = new ArrayList<String>();

    public static void main(String[] args) {
        System.out.println(PermutationDFS("abcd"));
    }

    public static ArrayList<String> PermutationDFS(String str) {
        if (str == null || str.equals("")) {
            return new ArrayList<>();
        }
        char[] chars = str.toCharArray();
        ArrayList<String> permutation = Permutation(chars, 0);
        ArrayList<String> strings = new ArrayList<>(permutation);
        Collections.sort(strings);
        return strings;
    }

    public static ArrayList<String> PermutationSwap(String str) {
        char[] s = str.toCharArray();
        perm(s, 0, str.length());
        HashSet h = new HashSet(list);
        list.clear();
        list.addAll(h);
        return list;
    }

    public static void perm(char[] str, int k, int len) {
        if (k == len - 1) {
            list.add(String.valueOf(str));
        } else {
            for (int i = k; i < len; i++) {
                swap(str, k, i);
                perm(str, k + 1, len);
                swap(str, k, i);
            }
        }

    }

    private static ArrayList<String> Permutation(char[] chars, int index) {
        ArrayList<String> result = new ArrayList<>();
        if (index == chars.length) {
            result.add(new String(chars));
        }
        for (int i = index; i < chars.length; i++) {
            swap(chars, i, index);
            ArrayList<String> permutation = Permutation(chars, index + 1);
            if (!result.containsAll(permutation)) {
                result.addAll(permutation);
            }
            swap(chars, i, index);
        }
        return result;
    }

    public static void swap(char[] arr, int a, int b) {
        char temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }

}
